package com.crcode.crm.controller.file;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crcode.crm.bean.user.UserBean;
import com.crcode.crm.utils.MyFileUtil;
import com.crcode.crm.utils.ExportExcelXTsts;

/**
 * 文件上传下载
 * @author cl
 * @date 2019年3月25日
 */
@Controller
public class FileController {
	
	/**
	 * 文件上传
	 * @author cl
	 * @date 2019年3月29日
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> fileUpload(HttpServletRequest request) throws UnsupportedEncodingException {
		Map<String, Object> map = new HashMap<String, Object>();
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		Object obj = session.getAttribute("user");
		UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
		if (user == null) {
			map.put("succ", false);
			map.put("msg", "用户未登录，请先登录！");
			return map;
		}
		String userXh = user.getUuid();
		// 上传文件位置
		try {
			// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			// 检查form中是否有enctype="multipart/form-data"
			if (multipartResolver.isMultipart(request)) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				String fileName = URLDecoder.decode(multiRequest.getParameter("fileName"), "UTF-8");
				String flag = multiRequest.getParameter("flag");
				String uploadPath = multiRequest.getParameter("uploadPath").replaceAll("//", "/")+ "/" + userXh + "/";
				Boolean fileStatus = false;
				// 获取multiRequest 中所有的文件名
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					// 一次遍历所有文件
					MultipartFile file = multiRequest.getFile(iter.next().toString());
					if (file != null) {
						byte[] bytes = file.getBytes();
						Map<String, Object> fm = MyFileUtil.uploadFile(bytes, uploadPath, fileName,flag);
						fileStatus = (Boolean) fm.get("status");
						if (fileStatus) {
							map.put("data", fm);
						}
					}
				}
				if (fileStatus) {
					map.put("succ", true);
					map.put("msg", "上传成功！");
				} else {
					map.put("succ", false);
					map.put("msg", "上传失败！");
				}
			}
		} catch (Exception e) {
			map.put("succ", false);
			map.put("msg", "文件上传异常！");
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 下载文件,文件名中文乱码前端处理
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/downloadFileWeb")
	public void dowanloadWeb(HttpServletRequest request,HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		//获取图片序号
		String filePath=URLDecoder.decode(request.getParameter("filePath"), "UTF-8");
		filePath = filePath.replaceAll("//", "/");
		String type=request.getParameter("downloadType");
		Map<String,Object> map = new HashMap<>();
		if(type.trim().equals("1")){
			map = MyFileUtil.downloadFile(filePath);
		}else{
			map = MyFileUtil.downloadZip("/"+filePath.split("/")[1],"附件");
		}
		byte[] bytes=(byte[]) map.get("bytes");
		String fileName=String.valueOf(map.get("fileName"));
		Long n=(long) map.get("fileLen");
		int fileLen=n.intValue();
		// 获取文件类型
		String fileType = fileName.substring(fileName.lastIndexOf("."));
		String title = fileName.substring(0, fileName.lastIndexOf("."));
		String path2 = title + fileType;
		//前端处理浏览器版本
		path2=URLEncoder.encode(path2, "UTF-8");
		response.setContentLength(fileLen);
		response.setHeader("Content-Disposition", "attachment;filename="+ path2);// 设置在下载框默认显示的文件名
		response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
		//读出文件
		InputStream fileInputStream = new ByteArrayInputStream(bytes); 
		BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
		byte[] arr = new byte[1024];// 自定义字节数组
		OutputStream outputStream = response.getOutputStream();
		int len;
		while ((len = bufferedInputStream.read(arr)) != -1) {
			outputStream.write(arr, 0, len);// 写出字节数组写出有效个字节个数
		}
		// 人走带门关闭输出流
		bufferedInputStream.close();
		outputStream.flush();
		outputStream.close();				
	}
	
	/**
	 * 下载文件，文件名中文乱码后端处理
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/downloadFileServer")
	public void dowanloadServer(HttpServletRequest request,HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		//获取图片序号
		JSONObject obj = JSON.parseObject(request.getParameter("datas"));
		String filePath=obj.getString("filePath"); 
		String type =obj.getString("downloadType"); 
		Map<String,Object> map = new HashMap<>();
		if(type.trim().equals("1")){
			map = MyFileUtil.downloadFile(filePath);
		}else{
			map = MyFileUtil.downloadZip("/"+filePath.split("/")[1],"附件");
		}
		byte[] bytes=(byte[]) map.get("bytes");
		String fileName=String.valueOf(map.get("fileName"));
		Long n=(long) map.get("fileLen");
		int fileLen=n.intValue();
		// 获取文件类型
		String fileType = fileName.substring(fileName.lastIndexOf("."));
		String title = fileName.substring(0, fileName.lastIndexOf("."));
		String path2 = title + fileType;
		//后端处理浏览器版本
		String getHeader=request.getHeader("User-Agent").toLowerCase();
		if (getHeader.indexOf("firefox") > 0) {    
			path2 = new String(path2.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器    
	    }else if (getHeader.indexOf("CHROME") > 0 && getHeader.indexOf("EDGE")==-1) {    
	    	path2 = new String(path2.getBytes("UTF-8"), "ISO8859-1");// 谷歌    
		}else{
			path2 = URLEncoder.encode(path2, "UTF-8");// IE浏览器    
		}  
		response.setContentLength(fileLen);
		response.setHeader("Content-Disposition", "attachment;filename="+ path2);// 设置在下载框默认显示的文件名
		response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
		//读出文件
		InputStream fileInputStream = new ByteArrayInputStream(bytes); 
		BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
		byte[] arr = new byte[1024];// 自定义字节数组
		OutputStream outputStream = response.getOutputStream();
		int len;
		while ((len = bufferedInputStream.read(arr)) != -1) {
			outputStream.write(arr, 0, len);// 写出字节数组写出有效个字节个数
		}
		// 人走带门关闭输出流
		bufferedInputStream.close();
		outputStream.flush();
		outputStream.close();				
	}
	
	/**
	 * 导出表格
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/exportExcel")
	public void exportExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String datas=request.getParameter("datas");
		ExportExcelXTsts ee=new ExportExcelXTsts();
		//获取要导出的数据
		JSONObject obj=JSONObject.parseObject(datas);
		//获取日志用参数
		OutputStream out = null;
		// 添加http头信息
		response.setContentType("octets/stream");
		// 设置要下载文件的文件名称
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String dateString = formatter.format(currentTime);
		//设置文件标题
		String wjtitle = "";
		String type=obj.getString("type");
		if("enter".equals(type)){
			wjtitle = "企业数据";
		}else if("project".equals(type)){
			wjtitle = "项目数据";
		}else if("log".equals(type)){
			wjtitle = "日志数据";
		}
		//后端处理浏览器版本
		String filename=wjtitle+dateString+ ".xls";
		String getHeader=request.getHeader("User-Agent").toLowerCase();
		if (getHeader.indexOf("firefox") > 0) {    
			filename = new String(filename.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器    
	    }else if (getHeader.indexOf("CHROME") > 0 && getHeader.indexOf("EDGE")==-1) {    
	    	filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");// 谷歌    
		}else{
			filename = URLEncoder.encode(filename, "UTF-8");// IE浏览器    
		}  
		//设置文件名
		response.addHeader("Content-Disposition", "attachment;filename="+filename);
		out = response.getOutputStream();
		//导出excel
		ee.exportExcel(out,obj,wjtitle);
		out.close();			
	}
	
}
